//
//  PPCategoryViewController.m
//  PPDL
//
//  Created by 王洋 on 2019/10/17.
//  Copyright © 2019 王洋. All rights reserved.
//

#import "PPLabTableViewCell.h"
#import "PPLabCollectionViewCell.h"

#import "PPCategorySectionHeadView.h"
#import "PPCategorySectionFootView.h"

#import "HomeSubscriptButton.h"

#import "GoodListViewController.h"
#import "PPCategoryViewController.h"
#import "MessageCenterViewController.h"

#define tableviewWidth      0.22 * TTScreenWidth

@interface PPCategoryViewController ()
<UITextFieldDelegate,
UITableViewDelegate,
UITableViewDataSource,
UICollectionViewDelegate,
UICollectionViewDataSource>{
    
    CGSize _cellSize;
    UIEdgeInsets _collectionEdge;
}

@property (nonatomic, strong) UITextField *searchTextField;

@property (nonatomic, strong) HomeSubscriptButton *messageItem;

@property (nonatomic, strong) UITableView *tableview;

@property (nonatomic, strong) UICollectionView *collectionview;

@property (nonatomic, strong) NSMutableArray <PPCategoryModel *> *categoryArray;

@property (nonatomic, assign) NSInteger selectIndex;

@end

@implementation PPCategoryViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self initView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self request_CategoryList];

    [self refreshUnReadMsgCount];
}

#pragma mark 去消息中心
- (void)goMsgCenter {
    [self.navigationController pushViewController:[MessageCenterViewController new] animated:YES];
}

#pragma mark 刷新未读消息数
- (void)refreshUnReadMsgCount {
    
    [self.messageItem setCountNum:0];
}

- (void)request_CategoryList {
    
    self.selectIndex = 0;
    NSMutableDictionary *dic = @{}.mutableCopy;
    NSString *url = [NSString stringWithFormat:@"%@%@",TT_Global_Api_Domain,TT_SHOP_CATEGORY];
    [TTHttpManager postRequestWithUrl:url TimeOut:10 PostData:dic FinishBlock:^(id  _Nonnull data) {
        
        [[TTNoResultManager shareManager] hideNoResultWithView:self.view];
        
        //返回data为字典
        if ([data isKindOfClass:[NSDictionary class]]) {
            NSString * code = [data valueForKey:@"code"];
            
            //请求成功
            if ([code isEqualToString:@"200"]) {
                
                //一级赋值
                NSArray *categoryArray = [data valueForKey:@"data"];
                self.categoryArray = @[].mutableCopy;
                if ([categoryArray isKindOfClass:[NSArray class]]) {
                    
                    for (int i = 0; i < categoryArray.count; i++) {
                        
                        NSDictionary *firstDic = categoryArray[i];
                        PPCategoryModel *firstModel = [[PPCategoryModel alloc] init];

                        if ([firstDic isKindOfClass:[NSDictionary class]]) {
                            
                            firstModel.itemTitle = [firstDic valueForKey:@"name"];
                            firstModel.itemID = [firstDic valueForKey:@"id"];
                            
                            if (i==0) {
                                firstModel.isSelect = YES;
                            }
                            
                            firstModel.childrens = @[].mutableCopy;
                            
                            //二级赋值
                            NSArray *secondArray = [firstDic valueForKey:@"child"];
                            if ([secondArray isKindOfClass:[NSArray class]]) {
                                for (int j = 0; j < secondArray.count; j++) {
                                    
                                    NSDictionary *secondDic = secondArray[j];
                                    PPCategoryModel *secondModel = [[PPCategoryModel alloc] init];
                                    
                                    secondModel.itemTitle = [secondDic valueForKey:@"name"];
                                    secondModel.itemID = [secondDic valueForKey:@"id"];
                                    
                                    secondModel.childrens = @[].mutableCopy;
                                    NSArray *thirdArray = [secondDic valueForKey:@"child"];
                                    
                                    if ([thirdArray isKindOfClass:[NSArray class]]) {
                                        
                                        for (int k = 0; k < thirdArray.count; k++) {
                                            
                                            NSDictionary *thirdDic = thirdArray[k];
                                            PPCategoryModel *thirdModel = [[PPCategoryModel alloc] init];
                                            thirdModel.itemTitle = [thirdDic valueForKey:@"name"];
                                            thirdModel.itemID = [thirdDic valueForKey:@"id"];
                                            
                                            [secondModel.childrens addObject:thirdModel];
                                        }
                                    }
                                    [firstModel.childrens addObject:secondModel];
                                }
                            }
                        }
                        [self.categoryArray addObject:firstModel];
                    }
                }
            } else {
                //检查到未登录
                if ([code isEqualToString:@"401"]) {
                    
                    [[TTUserModel sharedObject] initialization];
                    
                    [self openLoginWithCompletion:^(BOOL isLogin, NSDictionary * _Nonnull options) {
                        if (isLogin) {
                            [self request_CategoryList];
                        }
                    }];
                    
                } else {
                    
                    [SVProgressHUD showErrorWithStatus:[data valueForKey:@"msg"]];
                    [SVProgressHUD dismissWithDelay:1];
                    [[TTNoResultManager shareManager] showNoResultWithStateInView:self.view errorCode:kTTViewStateNoData btnTitle:@"重新加载" didPressButton:^{
                        [self request_CategoryList];
                    }];
                }
                
            }
        } else {
            
        }
        
        [self.tableview reloadData];
        [self.collectionview reloadData];
        
    } FailedBlock:^(NSError * _Nonnull error) {
        
        WEAKSELF
        [[TTNoResultManager shareManager] showNoResultWithStateInView:self.view errorCode:error.code btnTitle:@"重新加载" didPressButton:^{
            [weakSelf request_CategoryList];
        }];
        
    }];
    
}

- (void)initView {
    
    self.view.backgroundColor = UIColorHex(0xdddddd);
    
    CGFloat width = TTScreenWidth - tableviewWidth  - 1;
    CGFloat cellWidth;
    CGFloat distance = 8;
    cellWidth = width/3 - 2*distance;
    _cellSize =  CGSizeMake(cellWidth, 30);
    _collectionEdge = UIEdgeInsetsMake( distance, distance,  distance, distance);
    
    [self.view addSubview:self.tableview];
    [self.view addSubview:self.collectionview];
    
    self.navigationItem.titleView = self.searchTextField;
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.messageItem];
    
    self.searchTextField.frame = CGRectMake(0, 0, TTScreenWidth - 30, 32);
    
    [self.tableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0.5);
        make.left.bottom.mas_equalTo(0);
        make.width.mas_equalTo(tableviewWidth);
    }];
    
    [self.collectionview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0.5);
        make.left.mas_equalTo(self.tableview.mas_right).offset(0.5);
        make.right.bottom.mas_equalTo(0);
    }];    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self doSearchAction];
    
    return YES;
}

- (void)doSearchAction {

    [self.searchTextField resignFirstResponder];

    if (self.searchTextField.text.length) {
        GoodListViewController *VC = [[GoodListViewController alloc] init];
        VC.itemTitle = self.searchTextField.text;;
        VC.type = PP_GOODLIST_TYPE_SEARCH;
        [self.navigationController pushViewController:VC animated:YES];
    } else {
        [self alert:@"请输入搜索词"];
    }
}

#pragma mark tableview delegate & datasource

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    PPLabTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"PPLabTableViewCellID" forIndexPath:indexPath];
    
    if (self.categoryArray.count > indexPath.row) {
        [cell fillCellWithModel:self.categoryArray[indexPath.row]];
    }

    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.categoryArray.count;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    self.selectIndex = indexPath.row;
    
    for (int i = 0; i < self.categoryArray.count; i++) {
        
        if (i!=indexPath.row) {
            self.categoryArray[i].isSelect = NO;
        } else {
            self.categoryArray[i].isSelect = YES;
        }
    }
    
//    if (self.categoryArray[self.selectIndex].childrens.count != 0) {
//        
//        [[TTNoResultManager shareManager] hideNoResultWithView:self.collectionview];
//
//    } else {
//
//        [[TTNoResultManager shareManager] showNoResultWithStateInView:self.collectionview errorCode:kTTViewStateNoData btnTitle:@"" didPressButton:^{
//            
//        }];
//    }
    
    
    [self.tableview reloadData];
    [self.collectionview reloadData];
}

#pragma mark collectionview delegate & datasource
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    PPLabCollectionViewCell *cell;
    if (!cell) {
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PPLabCollectionViewCellID" forIndexPath:indexPath];
    }
    
    if (self.categoryArray.count > self.selectIndex && self.categoryArray[self.selectIndex].childrens.count > indexPath.section && self.categoryArray[self.selectIndex].childrens[indexPath.section].childrens.count > indexPath.row) {
            [cell fillCellWithModel:self.categoryArray[self.selectIndex].childrens[indexPath.section].childrens[indexPath.row]];
    }
    return cell;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView
           viewForSupplementaryElementOfKind:(NSString *)kind
                                 atIndexPath:(NSIndexPath *)indexPath {
    
    if ([kind isEqualToString:UICollectionElementKindSectionFooter]) {
        
        PPCategorySectionFootView *collectionFootView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"PPCategorySectionFootViewID" forIndexPath:indexPath];
        
        return collectionFootView;
        
    } else {
        
        PPCategorySectionHeadView *collectionHeadView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"PPCategorySectionHeadViewID" forIndexPath:indexPath];
        
        if (self.categoryArray.count > self.selectIndex && self.categoryArray[self.selectIndex].childrens.count > indexPath.section) {
            [collectionHeadView fillHeadWithModel:self.categoryArray[self.selectIndex].childrens[indexPath.section]];
        }
        
        return collectionHeadView;
    }

}

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    
    if (self.categoryArray.count > self.selectIndex) {
        return self.categoryArray[self.selectIndex].childrens.count;
    } else {
        return 0;
    }
    
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    if (self.categoryArray.count > self.selectIndex && self.categoryArray[self.selectIndex].childrens.count > section) {
        return self.categoryArray[self.selectIndex].childrens[section].childrens.count;
    } else {
        return 0;
    }
    
}

-(CGSize)collectionView:(UICollectionView *)collectionView
                 layout:(UICollectionViewLayout *)collectionViewLayout
 sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return _cellSize;
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView
                       layout:(UICollectionViewLayout *)collectionViewLayout
       insetForSectionAtIndex:(NSInteger)section {
    return _collectionEdge;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (self.categoryArray.count > self.selectIndex && self.categoryArray[self.selectIndex].childrens.count > indexPath.section&& self.categoryArray[self.selectIndex].childrens[indexPath.section].childrens.count > indexPath.row ) {
        
        for (PPCategoryModel *secondModel in self.categoryArray[self.selectIndex].childrens) {
            for (PPCategoryModel *thirdModel in secondModel.childrens) {
                thirdModel.isSelect = NO;
            }
        }
        self.categoryArray[self.selectIndex].childrens[indexPath.section].childrens[indexPath.row].isSelect = YES;
        [self.collectionview reloadData];
        
        GoodListViewController *VC = [[GoodListViewController alloc] init];
        VC.itemTitle = self.categoryArray[self.selectIndex].childrens[indexPath.section].childrens[indexPath.row].itemTitle;
        VC.type = PP_GOODLIST_TYPE_CATEGORY;
        VC.categoryID = self.categoryArray[self.selectIndex].childrens[indexPath.section].childrens[indexPath.row].itemID;
        [self.navigationController pushViewController:VC animated:YES];
    }
}

- (UITableView *)tableview {
    if (!_tableview) {
        _tableview = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableview.backgroundColor = PP_Default_Color_Gray_F1F1F1;
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableview.showsHorizontalScrollIndicator = NO;
        _tableview.showsVerticalScrollIndicator = NO;
        
        _tableview.estimatedSectionHeaderHeight = 0;
        _tableview.estimatedSectionFooterHeight = 0;
        _tableview.estimatedRowHeight = 0;
        
        [_tableview registerNib:[UINib nibWithNibName:@"PPLabTableViewCell" bundle:nil] forCellReuseIdentifier:@"PPLabTableViewCellID"];

    }
    return _tableview;
}

- (UICollectionView *)collectionview {
    if (!_collectionview) {
        
        UICollectionViewFlowLayout * flowLayout = [[UICollectionViewFlowLayout alloc]init];
        
        flowLayout.footerReferenceSize =CGSizeMake(TTScreenWidth, 5);
        flowLayout.headerReferenceSize =CGSizeMake(TTScreenWidth, 50);
        
        _collectionview  = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 0, 0) collectionViewLayout:flowLayout];
        _collectionview.delegate = self;
        _collectionview.dataSource = self;
        
        _collectionview.showsVerticalScrollIndicator = NO;
        _collectionview.showsHorizontalScrollIndicator = NO;
        
        _collectionview.backgroundColor = UIColorHex(0xffffff);
        
        [_collectionview registerNib:[UINib nibWithNibName:@"PPLabCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"PPLabCollectionViewCellID"];
        
        [_collectionview registerClass:[PPCategorySectionHeadView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"PPCategorySectionHeadViewID"];
        
        [_collectionview registerClass:[PPCategorySectionFootView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"PPCategorySectionFootViewID"];
    }
    return _collectionview;
}

- (UITextField *)searchTextField {
    if (!_searchTextField) {
        _searchTextField = [[UITextField alloc]init];
        _searchTextField.backgroundColor = UIColorHex(0xf0f0f0);
        _searchTextField.delegate = self;
        _searchTextField.returnKeyType = UIReturnKeySearch;
        _searchTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        _searchTextField.placeholder = @"输入关键词搜索";
        _searchTextField.font = [UIFont fontWithName:@"Arial" size:14];
        _searchTextField.frame = CGRectMake(0, 6, TTScreenWidth - 60, 32);
        _searchTextField.layer.cornerRadius = 6;
        _searchTextField.layer.masksToBounds = YES;
        
        UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        searchBtn.frame = CGRectMake(0, 0, 30, 30);
        searchBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
        [searchBtn addTarget:self action:@selector(doSearchAction) forControlEvents:UIControlEventTouchUpInside];
        [searchBtn setImage:[UIImage imageNamed:@"search_icon"] forState:UIControlStateNormal];
        
        _searchTextField.leftView = searchBtn;
        _searchTextField.leftViewMode = UITextFieldViewModeAlways;
    }
    return _searchTextField;
}

- (NSMutableArray<PPCategoryModel *> *)categoryArray {
    if (!_categoryArray) {
        _categoryArray = @[].mutableCopy;
    }
    return _categoryArray;
}

- (HomeSubscriptButton *)messageItem {
    if (!_messageItem) {
        _messageItem = [[HomeSubscriptButton alloc] initWithSize:CGSizeMake(40, 40)];
        [_messageItem.topButton setImage:[UIImage imageNamed:@"homeMsg"] forState:UIControlStateNormal];;
        _messageItem.userInteractionEnabled = YES;
        [_messageItem.topButton addTarget:self action:@selector(goMsgCenter) forControlEvents:UIControlEventTouchUpInside];
    }
    return _messageItem;
}
@end
